package glfw

import (
	inputparam "learn-opengl/inputParam"
	"log"

	"github.com/go-gl/gl/v3.3-core/gl"
	"github.com/go-gl/glfw/v3.2/glfw"
)




func InitGl(input *inputparam.Inputparam,w, h int) *glfw.Window {
	// 初始化glfw
	err := glfw.Init()
	if err != nil {
		log.Fatal(err)
	}
	glfw.WindowHint(glfw.Resizable, glfw.False)
	// 设置opengl版本3.3
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	// 开启智能指针等支持
	glfw.WindowHint(glfw.OpenGLForwardCompatible, gl.TRUE)


	// 创建窗口
	win, err := glfw.CreateWindow(w, h, "linYuanMicraft", nil, nil)
	if err != nil {
		log.Fatal(err)
	}
	// 输入管理
	win.SetInputMode(glfw.CursorMode,glfw.CursorDisabled)
	win.SetCursorPos(0,0)
	win.SetKeyCallback(func(w *glfw.Window, key glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) {
		if(key == glfw.KeyEscape && action == glfw.Press) {
			win.SetShouldClose(true)
		}
		if(key >= 1024 || key <=0) {
			return 
		}
		if(action == glfw.Press) {
			input.Keys[key] = true
		}
		if(action == glfw.Release) {
			input.Keys[key] = false
		}
	})
	win.SetScrollCallback(func(w *glfw.Window, xoff, yoff float64) {
		input.Scroll_offset = float32(yoff)
	})
	win.SetCursorPosCallback(func(w *glfw.Window, xpos, ypos float64) {
		input.Delte_mouse_X = (float32(xpos) - input.Mouse_x)
		input.Delte_mouse_Y = (input.Mouse_Y - float32(ypos))
		input.Mouse_x = float32(xpos)
		input.Mouse_Y = float32(ypos)
	})
	win.SetMouseButtonCallback(func(w *glfw.Window, button glfw.MouseButton, action glfw.Action, mod glfw.ModifierKey)  {
		if button == glfw.MouseButton1 && action == glfw.Press {
			input.Button1 = true
		}
		if button == glfw.MouseButton2 && action == glfw.Press {
			input.Button2 = true
		}
	})

	win.MakeContextCurrent()

	err = gl.Init()
	if err != nil {
		log.Fatal(err)
	}

	// 开启垂直同步
	glfw.SwapInterval(1) 
	// 允许深度测试
	gl.Enable(gl.DEPTH_TEST)
	// 开启背面剔除
	gl.Enable(gl.CULL_FACE)
	// 设置opengl显示范围
	gl.Viewport(0,0,int32(w),int32(h))
	return win

}
